import React, { useState } from 'react'
import { Card, Form, Input, Button, message, Checkbox } from 'antd'
import { UserOutlined, LockOutlined, EyeInvisibleOutlined, EyeTwoTone } from '@ant-design/icons'
import { useNavigate } from 'react-router-dom'
import { mockApi } from '@/services/mockData'

const Login: React.FC = () => {
  const [loading, setLoading] = useState(false)
  const [showPassword, setShowPassword] = useState(false)
  const navigate = useNavigate()
  const [form] = Form.useForm()

  const handleLogin = async (values: { username: string; password: string; remember: boolean }) => {
    setLoading(true)
    try {
      const result = await mockApi.login(values.username, values.password)
      if (result.success) {
        // 存储登录状态
        const userInfo = {
          username: values.username,
          isAdmin: result.isAdmin || false,
          loginTime: new Date().toISOString()
        }
        
        if (values.remember) {
          localStorage.setItem('userInfo', JSON.stringify(userInfo))
        } else {
          sessionStorage.setItem('userInfo', JSON.stringify(userInfo))
        }
        
        message.success('登录成功')
        
        // 根据用户类型跳转到不同页面
        if (result.isAdmin) {
          navigate('/dashboard')
        } else {
          navigate('/user-dashboard')
        }
      } else {
        message.error(result.message)
      }
    } catch (error) {
      message.error('登录失败，请重试')
    } finally {
      setLoading(false)
    }
  }

  const handleRegister = () => {
    navigate('/register')
  }

  // 解决背景未铺满和滚动条问题
  return (
    <div style={{
      position: 'fixed',
      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
      height: '100vh',
      width: '100vw',
      backgroundImage: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      padding: '20px',
      boxSizing: 'border-box',
      margin: 0,
      overflow: 'hidden'
    }}>
      <Card 
        title="乡村产业发展平台登录" 
        extra={undefined}
        headStyle={{ paddingBottom: 0 }}
        style={{ 
          // 使用响应式宽度，最大400px
          width: '100%',
          maxWidth: 400,
          borderRadius: 12,
          boxShadow: '0 8px 24px rgba(0,0,0,0.12)',
          background: 'rgba(255,255,255,0.95)',
          // 确保在移动设备上有足够的内边距
          padding: '24px'
        }}
      >
        <Form
          form={form}
          name="login"
          layout="vertical"
          onFinish={handleLogin}
        >
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input
              prefix={<UserOutlined className="site-form-item-icon" />}
              placeholder="请输入用户名"
              size="large"
            />
          </Form.Item>
          
          <Form.Item
            name="password"
            label="密码"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password
              prefix={<LockOutlined className="site-form-item-icon" />}
              placeholder="请输入密码"
              size="large"
              iconRender={(visible) => (
                visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />
              )}
              visibilityToggle={{ visible: showPassword, onVisibleChange: setShowPassword }}
            />
          </Form.Item>
          
          <Form.Item name="remember" valuePropName="checked" className="mb-4">
            <Checkbox>记住我</Checkbox>
          </Form.Item>
          
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              style={{ width: '100%' }}
              size="large"
              loading={loading}
            >
              登录
            </Button>
          </Form.Item>
          
          <div style={{ textAlign: 'center', marginTop: 16 }}>
            <Button type="link" onClick={handleRegister}>
              还没有账号？立即注册
            </Button>
          </div>
        </Form>
      </Card>
    </div>
  )
}

export default Login